import React, {  useState, useEffect,useMemo } from 'react';
import { Text, View,Button,Image,Input,navigateTo, usePageEvent,hideMenuButton,getStorage,setStorage,useAppEvent,getLaunchOptionsSync,queryDps,onDpDataChange,registerDeviceListListener,getDpsInfos,changeDebugMode   } from '@ray-js/ray';
import styles from './index.module.less';
import ball from '../../assets/images/tab/ball.png'
import grow from '../../assets/images/tab/grow.png'
import space from '../../assets/images/tab/space.png'
import card from '../../assets/images/tab/card.png'
import electric from '../../assets/images/tab/electric.png'
import charging from '../../assets/images/tab/charging.png'
import { useActions, useProps } from '@ray-js/panel-sdk';
import { volumeSetCode,batteryPercentageCode,chargeStatusCode,dev_name_code,user_name_code,volume_mute_code,request_dp_code } from '@/constant/dpCodes';
import { devices } from '@/devices';
import throttle from 'lodash/throttle';
import { Slider } from '@ray-js/smart-ui';
import Rename_popup from '../../components/rename_popup';
import { device } from '@ray-js/ray'
const { openDeviceDetailPage } = device
import DailyPopup from '../../components/DailyPopup';
import Popup from '../../components/popup';
import { utils } from '@ray-js/panel-sdk';
const { parseHour12 } = utils;
const { stringToSecond } = utils;
import {requestWifiSignal,getAI2AgentVariableAgentVariableList,updateAI2AgentVariableAgentVariable,getAI2AgentRoles,bindAI2AgentRoles,getAccountInfo   } from '@ray-js/ray'
import {emojitest} from './emojiData.jsx'
import FlowerLetter from '../../components/FlowerLetter';
import { set } from 'lodash-es';

type charge_status = 'charging' | 'none' | 'charge_done';

//通过不同的BatteryValue值返回不同的图标类名
const getBatteryIconClass = (batteryValue) => {
  if (batteryValue >= 90) return 'icon-battery100';
  if (batteryValue >= 70) return 'icon-battery70';
  if (batteryValue >= 50) return 'icon-battery50';
  if (batteryValue >= 30) return 'icon-battery30';
  if (batteryValue >= 10) return 'icon-battery10';
  if (batteryValue >= 0) return 'icon-battery0';
}

//根据时间戳计算天数差
function getDayDifference(timestamp1, timestamp2) {
  // 1 天 = 24 小时 × 60 分钟 × 60 秒 = 86400 秒
  const secondsPerDay = 86400;
  
  // 计算时间差（绝对值）
  const diffSeconds = Math.abs(timestamp1 - timestamp2);
  
  // 计算完整天数
  return Math.floor(diffSeconds / secondsPerDay);
}

//获取开始时时间戳
function getTodayStartTimestamp() {
  const now = new Date();
  now.setHours(0, 0, 0, 0); // 设置为当天的00:00:00.000
  return Math.floor(now.getTime() / 1000); // 转换为秒级时间戳
}

export default function New_toy_home(){
  const [BatteryValue,setBatteryValue]=useState(20);
  let dpVolumeSet = useProps(props => props[volumeSetCode]);
  useEffect(()=>{
    //刚进入首页时发出DP请求获取DP值
    const { query: { deviceId } } = getLaunchOptionsSync();
    let roleid;
    
    const BindAI=async()=>{         //绑定智能体角色
      try{
        const result=await bindAI2AgentRoles({  
          devId: deviceId,  
          roleId: roleid  
        });
        console.log('绑定结果',result)
      } catch(error){
        console.log(error)
      }
    }

    const fetchAI=async()=>{
      try{
        const result=await getAI2AgentRoles({  
          devId: deviceId,  
          pageNo: 1,  
          pageSize: 10  
        });
        roleid=result.list[0].roleId;
        console.log('智能体角色列表',result)
        BindAI()
      } catch(error){
        console.log(error)
      }

    }
    fetchAI()

    getDpsInfos({
      devId: deviceId,
      gwId: deviceId,
    })
    
      .then(res => {
        const initialbattery = Number(res.find(user => user.code === 'battery_percentage')?.value);
        const chargestatus = res.find(user => user.code === 'charge_status')?.value;
        dpVolumeSet=Number(res.find(user => user.code === 'volume_set')?.value);
        const initialismute=res.find(user => user.code === 'volume_mute')?.value;
        const boolinitialismute=initialismute==='true';
        if (chargestatus === 'charging' || chargestatus === 'none' || chargestatus === 'charge_done') {
          setCharge(chargestatus); 
        }
        setBatteryValue(initialbattery);
        setisMute(boolinitialismute);
      })
      .catch(error => {
        console.log(error);
      });

    //刚进入首页时根据球球虚拟ID不同去分配值
    getStorage({
      key:deviceId,
      success(res){
        if(res.data===null)     //设置初始值
        {
          setday(1);
          const Start=getTodayStartTimestamp();
          const InitialBattery=20;
          setStorage({
            key:deviceId,
            data:{
              StartTimeStamp:Start,
              battery:InitialBattery
            }
          })
        }
      }
    })
  },[])
  const [day,setday]=useState(0);

  //跳转到成长花园
  const navigateTogrow=()=>{
    navigateTo({ 
      url:'/pages/grow/index',
     })
  }

  //跳转到空间智能
  const navigateTospace=()=>{
    navigateTo({ 
      url:'/pages/space/index',
     })
  }

  //电池电量获取
  const dpBattery = useProps(props=>props[batteryPercentageCode]);
  const [isFirstLoad3,setisFirstLoad3]=useState(true);
  useEffect(() => {
    if(isFirstLoad3)
    {
      setisFirstLoad3(false);
      return;
    }
    setBatteryValue(dpBattery);
  }, [dpBattery]);

  //充电状态获取
  const [Charge, setCharge] = useState<charge_status>('none');
  const changeCharge = (newType: string) => {
    const validTypes: charge_status[] = ['charging', 'none', 'charge_done'];
    if (validTypes.includes(newType as charge_status)) {
      setCharge(newType as charge_status);
    } else {
      console.error('无效的类型:', newType);
    }
  };
  const dpCharge = useProps(props=>props[chargeStatusCode]);
  useEffect(() => {
    changeCharge(dpCharge);
  }, [dpCharge]);

  //音量键操作
  const [voice_exist,setvoice_exist]=useState(false);
  const voice_change=()=>{
    // 音量静音逻辑
    if(isMute===true)
    {
      setisMute(false);
      actions[volume_mute_code]?.set(false);
      actions[volumeSetCode]?.set(dpVolumeSet);
    }

    if(voice_exist){
      setvoice_exist(false);
    }
    else{
      setvoice_exist(true);
    }
  }

  //音量设置
  const actions = useActions();
  const {
    property: { min = 0, max = 100 },
  } = devices.common.getDpSchema()[volumeSetCode] || { property: { min: 0, max: 100 } };
  const handleAfterChange = useMemo(
    () =>
      throttle((value: number) => {
        actions[volumeSetCode]?.set(value), { debounce: 200 };
      }, 200),
    [actions]
  );
  useEffect(()=>{
    if(dpVolumeSet===0)
    {
      setisMute(true);
      actions[volume_mute_code]?.set(true);
    }
  },[dpVolumeSet])

  //球球和主人的名字
  const [BallName,setBallName]=useState('球球');
  const [HostName,setHostName]=useState('');
  
    //在用户名称和球球名称改变时上报一次DP
  // useEffect(()=>{
  //   if(BallName==='')     //如果是空数据
  //   {
  //     return;
  //   }
  //   actions[dev_name_code].set(BallName);
  // },[BallName])
  useEffect(()=>{
    if(HostName==='')   //如果是空数据
    {
      return;
    }
    actions[user_name_code].set(HostName);
  },[HostName])

  //重命名的弹窗
  const [show_popup,setshow_popup]=useState(false);
  const Open_popup=()=>{
    setshow_popup(true);
  }
  const close=()=>{
    setshow_popup(false);
  }


  //打开设备详情页
  const open_device=()=>{
    const {
      query: { deviceId }
    } = getLaunchOptionsSync();
    openDeviceDetailPage({ 
      deviceId,
      success(res){
      },
      fail(res){
        console.log(res);
      }
     })
  }


  //每日卡片的颜色初始化
  const [DailyPopupcolor1,setDailyPopupcolor1]=useState(()=>{
    return emojitest.happy.color1
  });
  const [DailyPopupcolor2,setDailyPopupcolor2]=useState(()=>{
    return emojitest.happy.color2
  });
  const [DailyPopuptext1,setDailyPopuptext1]=useState(emojitest.happy.text.text1_2);
  const [DailyPopuptext2,setDailyPopuptext2]=useState(emojitest.happy.text.text1_1);
  const [DailyPopupExist,setDailyPopupExist]=useState(false);
  const [fireworksExist,setfireworksExist]=useState(false);
  //烟花效果
  useEffect(()=>{
    setfireworksExist(false);
  },[DailyPopupExist])
  //开关每日卡片
  const CloseDailyPopup =()=>{
    setDailyPopupExist(false);
  }
  const OpenDailyPopup=()=>{
    setDailyPopupExist(true);
  }

  //时间格式转换函数,例:2025.08.30这样的格式
  const TransformTimeFormat = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}.${month}.${day}`;
  };

  //时间格式转换函数,例:12:12:30这样的格式
  const formatWithColons = (date) => {
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
  };

  useEffect (()=>{
    const {query: { deviceId }} = getLaunchOptionsSync();
    //胶囊隐藏
    hideMenuButton({

    })

    //计算陪伴天数逻辑
    getStorage({
      key:deviceId,
      success(res){
        const End=getTodayStartTimestamp();
        const Start=Number(res.data.StartTimeStamp);
        const AccompanyDay=getDayDifference(End,Start);
        setday(AccompanyDay+1);
      }
    })
    //页面渲染时获取智能体变量主人和球球名字

    const FetchVariable=async()=>{
      try{
        const newVariables = await getAI2AgentVariableAgentVariableList({  
          devId: deviceId,  
        });
        const call = newVariables.find(user => user.variableKey === 'custom.call')?.variableValue;
        // const BallName = newVariables.find(user => user.variableKey === 'custom.ballName')?.variableValue;
        setHostName(call);
        // setBallName(BallName);
      } catch{
  
      }
    }
    
    FetchVariable();

    let RecentDate='';
    const second=stringToSecond(formatWithColons(new Date()));
    const CurrentDate=TransformTimeFormat(new Date());
    
    getStorage({
      key: deviceId+'4',
      success: async (res) => {
        RecentDate=res.data;
        if(res.data===null)
        {
          RecentDate='初始化';
        }
        
        //判断是不是超过早上八点且日期不同
        if((second>28800)&&(CurrentDate !== RecentDate))
          {
            
            //智能体用户心情变量获取
            let mood='happy';
            try {
              const { query: { deviceId } } = getLaunchOptionsSync();
              const newVariables = await getAI2AgentVariableAgentVariableList({  
                devId: deviceId,  
              });
              mood = newVariables.find(user => user.variableKey === 'custom.mood')?.variableValue;
            } catch (error) {         //如果获取不到变量就随机获取一个心情
              const moods = ['happy', 'calm', 'love', 'anxiety', 'sad', 'angry'];
              mood = moods[Math.floor(Math.random() * moods.length)];
            }
            
            //随机值获取
            const keystest=Object.keys(emojitest[mood].text);
            const randomKeytest = keystest[Math.floor(Math.random() * keystest.length)];
            const randomtext = emojitest[mood].text[randomKeytest];
            

            setfireworksExist(true);
            setDailyPopupExist(true);

           
            //将日期数据存储起来
            setStorage({
              key: deviceId+'4',
              data: CurrentDate,
              success: () => {
              },
              fail: (err) => {
                console.log(err);
              }              
            });  
            //将每日卡片内容（文字，颜色等）存储起来
            setStorage({
              key:deviceId+'5',
              data:{
                color1:emojitest[mood].color1,
                color2:emojitest[mood].color2,
                content1:randomtext.text1_1,
                content2:randomtext.text1_2
              },
              success(){
                setDailyPopupcolor1(emojitest[mood].color1);
                setDailyPopupcolor2(emojitest[mood].color2);
                setDailyPopuptext1(randomtext.text1_2);
                setDailyPopuptext2(randomtext.text1_1);
              }
            })
          }
          else{               //如果不符合每日更新卡片内容条件
            //取每日卡片内容并渲染
            getStorage({
              key:deviceId+'5',
              success(res)
              {
                setDailyPopupcolor1(res.data.color1);
                setDailyPopupcolor2(res.data.color2);
                setDailyPopuptext1(res.data.content2);
                setDailyPopuptext2(res.data.content1);
              }
            })
          }
      },
      fail: (err) => {

      }
    });
    
  },[])
  
  //信号强度
  const [Signal,setSignal]=useState(-100);
  useEffect(()=>{
    const {query: { deviceId }} = getLaunchOptionsSync();
     
    requestWifiSignal({
      deviceId,
      success: (signal) => {
        const num = Number(signal);
        setSignal(num);
      },
      fail: (error) => {
        setSignal(-100);
      }
    });
  },[])
  useEffect(() => {
    const timer = setInterval(async() => {
      
      const {
        query: { deviceId }
      } = getLaunchOptionsSync();
       
      requestWifiSignal({
        deviceId,
        success: (signal) => {
          const num = Number(signal);
          console.log('signal',signal)
          setSignal(num);
        },
        fail: (error) => {
          setSignal(-100);
          // console.log(error)
        }
      });

      try{
        const newVariables = await getAI2AgentVariableAgentVariableList({  
          devId: deviceId,  
        });
        const call = newVariables.find(user => user.variableKey === 'custom.call')?.variableValue;
        // const BallName = newVariables.find(user => user.variableKey === 'custom.ballName')?.variableValue;
        // setBallName(BallName);
        setHostName(call);
      } catch{

      }
      
    }, 3500);
    
    return () => clearInterval(timer); // 组件卸载时清除定时器
  }, [])

  //静音DP
  const [isMute,setisMute]=useState(false);
  const volumemute = useProps(props => props[volume_mute_code]);
  useEffect(()=>{
    setisMute(volumemute);
  },[volumemute])
  return(
    <>
      <View className={styles.box1}>
          <View className={styles.card_btn}  onClick={OpenDailyPopup}>
            <View className={styles.ImgBg}>
              <Image src={card} className={styles.btn_img}/>
            </View>
            <Text className={styles.card_font}>好运密码</Text>
          </View>

          <View className={styles.grow_btn}  onClick={navigateTogrow}>
            <View className={styles.ImgBg}>
              <Image src={grow} className={styles.btn_img}/>
            </View>
            <Text className={styles.grow_font}>成长花园</Text>
          </View>

          <View className={styles.space_btn}  onClick={navigateTospace}>
            <View className={styles.ImgBg}>
              <Image src={space} className={styles.btn_img}/>
            </View>
            <Text className={styles.space_font}>附近球球</Text>
          </View>
      </View>

      <Image src={ball} className={styles.ball}/>

      <View className={styles.circle}></View>

      <View className={styles.name_box}>
        <Text className={styles.name}>
            {HostName}的{BallName}
        </Text>
        <Button className={styles.rename_btn} onClick={Open_popup}>
          <Text className={`iconfont icon-edit ${styles.edit_icon}`}></Text>
        </Button>
      </View>

      {false && <Text className={styles.text2}>请告诉球球,它可以怎么称呼你</Text>}

      <Text className={styles.text1}>
        陪伴你的第<Text className={styles.day}>{day}</Text>天
      </Text>


      <View className={styles.bottom_menus_root}>

        <View className={styles.container}>

          <View className={`${styles.menu} ${styles['menu-charge']}`}>
              {Charge=='charging' && <Text className={`${styles.charging_icon} iconfont icon-lightning-full`}></Text>}
              <View className={`${styles.electric_box} ${BatteryValue<=30 ? styles.low : styles.middle}`}>
                 <View className={`iconfont ${getBatteryIconClass(BatteryValue)}`} style={{fontSize:'30px !important'}}></View>
              </View>
              <Text className={styles.electric_value}>{BatteryValue}%</Text>

          </View>


          <view className={styles.menu}>
            <view className={styles.menu_item} onClick={open_device}>
              <Text className={`iconfont ${Signal > -100 ? 'icon-wifi' : 'icon-no-wifi'} ${styles.menu_icon}`}></Text>
              <Text className={styles.wifi_font}>Wi-Fi信号</Text>
            </view>
          </view>

           
          <view className={styles.menu}>
            <view className={styles.menu_item} onClick={voice_change}>
              <Text className={`iconfont ${(dpVolumeSet===0 || isMute) ? 'icon-voice5-01':'icon-voice4-01'} ${styles.menu_icon}`}></Text>
              <Text className={styles.voice_font}>音量调节</Text>
            </view>
          </view>

        </View>


      </View>
    
      { voice_exist &&
        <Slider className={styles.slider}
              maxTrackHeight="200px"
              minTrackHeight="8px"
              minTrackWidth="5px"
              maxTrackWidth="5px"
              thumbHeight="15px"
              thumbWidth="15px"
              thumbColor="#8eb9f6"
              minTrackColor="#8eb9f6"
              min={min}
              max={max}
              value={dpVolumeSet}
              onAfterChange={handleAfterChange}
              moveEventName="sliderMove"
              isVertical
              style={{
                position:'absolute',
                bottom:'15%',
                right:'5%',
              }}
            />}

        { show_popup &&
          <Rename_popup onClose={close} currentBallName={BallName} currentHostName={HostName}/>}
        { show_popup &&
        <View className={styles.mask}/>}


        { DailyPopupExist &&
          <DailyPopup onClose={CloseDailyPopup} color1={DailyPopupcolor1} color2={DailyPopupcolor2} text1={DailyPopuptext1} text2={DailyPopuptext2} fireworks={fireworksExist}></DailyPopup>}
    </>
  )
}